package container

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/tabwriter"

	"gitee.com/chuanjinge/go-container/config"
	"gitee.com/chuanjinge/go-container/container/containerconfig"
	"gitee.com/chuanjinge/go-container/container/info"
)

type ContainerSet struct {
	list []*info.ContainerInfo
}

func NewContainerSet() *ContainerSet {
	return &ContainerSet{
		list: make([]*info.ContainerInfo, 0),
	}
}

func (cs *ContainerSet) ListAll() *ContainerSet {
	// 读取 /data/tinydocker/container 目录下的所有文件夹
	files, err := os.ReadDir(config.GlobalConfig().ContainerPath)
	if err != nil {
		log.Printf("read dir %s error %v", config.GlobalConfig().ContainerPath, err)
		return nil
	}

	for _, dir := range files {
		if dir.IsDir() {
			info, err := getContainerInfo(dir)
			if err == nil {
				cs.list = append(cs.list, info)
			}
		}
	}
	return cs
}

// 打印到控制台
func (cs *ContainerSet) Console() {
	var err error
	// tabwriter 是引用的text/tabwriter类库，用于在控制台打印对齐的表格
	writer := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)
	_, err = fmt.Fprintln(writer, "ID\tNAME\tPID\tRUNNING\tCOMMAND\tIP\tCREATED")
	if err != nil {
		log.Printf("Fprint error %v\n", err)
		return
	}

	for _, item := range cs.list {
		ipList := ""
		for _, v := range item.NetworkSettings.Networks {
			ipList += v.IPAddress + ","
		}
		ipList = strings.TrimRight(ipList, ",")
		fmt.Fprintf(writer, "%s\t%s\t%d\t%v\t%s\t%s\t%s\n",
			item.ID,
			item.Name,
			item.State.Pid,
			item.State.Running,
			item.Command,
			ipList,
			item.Created)
	}
	if err = writer.Flush(); err != nil {
		log.Printf("Flush error %v\n", err)
	}
}

func getContainerInfo(file os.DirEntry) (*info.ContainerInfo, error) {
	configFilePath := filepath.Join(config.GlobalConfig().ContainerPath, file.Name(), containerconfig.CONFIG_V2_LOG)
	return info.ReadConfigV2JsonAndUnmarshal(configFilePath)
}
